package com.yannuo.util;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class AuditLoggerInterceptor implements MethodInterceptor {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        String methodName = method.getName();
        LocalDateTime now = LocalDateTime.now();
        String timestamp = now.format(FORMATTER);
        System.out.println("[审计日志] " + timestamp + " 调用方法: " + methodName);

        if ("logSensitive".equals(methodName)) {
            if (args != null && args.length > 0 && args[0] instanceof String) {
                String sensitiveData = (String) args[0];
                int length = sensitiveData.length();
                int halfLength = length / 2;
                String maskedData = sensitiveData.substring(0, halfLength) + "****";
                args[0] = maskedData;
            }
        }

        if ("clearLogs".equals(methodName)) {
            throw new SecurityException("不允许清除日志");
        }

        return proxy.invokeSuper(obj, args);
    }
}